package servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;

import beans.Student;
import beans.StudentDao;
import jdk.nashorn.internal.runtime.JSONListAdapter;

@WebServlet("/ServletAPI")
public class ServletAPI extends HttpServlet {
	
	public ServletAPI() {
		super();
	}
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO Auto-generated method stub
		// super.doGet(req, resp);
		try {
			List<Student> list = StudentDao.getStudentList();
			Gson gson = new Gson();
			String json = gson.toJson(list);
			PrintWriter writer = resp.getWriter();
			writer.write(json);
			writer.flush();
			writer.close();
			
			
			resp.setContentType("application/json");
			resp.setCharacterEncoding("utf-8");
			resp.getWriter().append(json);
			
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(req, resp);
	}
}
